package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    @Override
    public PageInfo<?> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list=strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {

        if(strategyDetail.getSequence()==null){
            Integer max=strategyDetailMapper.selectMaxSequence(strategyDetail.getCatalog().getId());
            if(max != null){
                strategyDetail.setSequence(max+1);
            }else {
                strategyDetail.setSequence(0);
            }
        }

        StrategyContent strategyContent = strategyDetail.getStrategyContent();

        if (strategyDetail.getId() == null) {

            strategyDetail.setCreateTime(new Date());
            if(strategyDetail.getState()!= StrategyDetail.STATE_RELEASE){
               strategyDetail.setReleaseTime(new Date());
            }

            strategyDetailMapper.insert(strategyDetail);
            strategyContent.setId(strategyDetail.getId());
            contentMapper.insert(strategyContent);
        } else {
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            strategyContent.setId(strategyDetail.getId());
            contentMapper.updateByPrimaryKey(strategyContent);
        }
    }

    @Override
    public StrategyContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    @Override
    public StrategyDetail getDetailId(Long id) {
        return strategyDetailMapper.getDetailId(id);
    }

    @Override
    public PageInfo<?> queryBystate(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list=strategyDetailMapper.queryBystate(qo);
        return new PageInfo<>(list);
    }
}
